package com.xiaouyudeguang.common.client;

import com.xiaouyudeguang.common.exception.BusinessException;
import com.xiaouyudeguang.common.model.AMapAddress;
import com.xiaouyudeguang.common.utils.JsonObject;
import com.xiaouyudeguang.common.utils.MapModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;


@Component
@Slf4j
public class AMapClient {

    @Value("${api.amap.key}")
    private String amapKey;

    public AMapAddress getAddress(String address) throws Exception {
        StringBuilder result = new StringBuilder();
        String reqUrl = String.format("http://restapi.amap.com/v3/geocode/geo?key=%s&address=%s", amapKey, address);
        log.info("reqUrl.{}", reqUrl);
        URL url = new URL(reqUrl);
        URLConnection conn = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        in.close();
        log.info("result.{}", result);
        MapModel<String, Object> map = JsonObject.toMap(result.toString());
        if (!"1".equals(map.getText("status"))) {
            throw new BusinessException("地址" + address + "匹配坐标失败");
        }
        List<String> geocodes = JsonObject.toList(map.get("geocodes"));
        if (geocodes == null || geocodes.size() == 0) {
            throw new BusinessException("地址" + address + "匹配坐标失败");
        }
        MapModel<String, Object> geocode = JsonObject.toMap(geocodes.get(0));
        AMapAddress mapAddress = new AMapAddress();
        mapAddress.setDetails(geocode.getText("formatted_address"));
        mapAddress.setLongitude(geocode.getText("location").split(",")[0]);
        mapAddress.setLatitude(geocode.getText("location").split(",")[1]);
        mapAddress.setAdministrativeArea(geocode.getText("country") + geocode.getText("province") + geocode.getText("city") + geocode.getText("district"));
        if (geocode.getText("formatted_address").equals(geocode.getText("province"))) {
            mapAddress.setAdministrativeAreaCode(geocode.getText("adcode"));
        } else {
            String administrativeAreaCode = geocode.getText("adcode");
            if (!administrativeAreaCode.endsWith("0000")) {
                if (administrativeAreaCode.endsWith("00")) {
                    administrativeAreaCode = administrativeAreaCode.substring(0, 2) + "0000," + administrativeAreaCode;
                } else {
                    administrativeAreaCode = administrativeAreaCode.substring(0, 2) + "0000," + administrativeAreaCode.substring(0, 4) + "00," + administrativeAreaCode;
                }
            }
            List<String> township = JsonObject.toList(geocode.get("township"));
            mapAddress.setAdministrativeAreaCode(administrativeAreaCode + (township.size() == 0 ? "" : township.get(0)));
            log.info("result.administrativeAreaCode.{}", administrativeAreaCode);
        }
        return mapAddress;
    }

//    public String getAdministrativeAreaCode(String province, String address, String adcode) throws Exception {
//        StringBuilder result = new StringBuilder();
//        String reqUrl = String.format("https://restapi.amap.com/v3/config/district?key=%s&keywords==%s&subdistrict=3", amapKey, province);
//        log.info("reqUrl.{}", reqUrl);
//        URL url = new URL(reqUrl);
//        URLConnection conn = url.openConnection();
//        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//        String line;
//        while ((line = in.readLine()) != null) {
//            result.append(line);
//        }
//        in.close();
//        log.info("result.{}", result);
//        MapModel<String, Object> map = JsonObject.toMap(result.toString());
//        if (!"1".equals(map.getText("status"))) {
//            throw new BusinessException("获取" + province + "行政区划失败");
//        }
//        List<String> provinceDistricts = JsonObject.toList(map.get("districts"));
//        if (provinceDistricts == null || provinceDistricts.size() == 0) {
//            throw new BusinessException("地址" + address + "匹配行政区划失败");
//        }
//        for (int i = 0; i < provinceDistricts.size(); i++) {
//
//        }
//        MapModel<String, Object> district = JsonObject.toMap(districts.get(0));
//        AMapAddress mapAddress = new AMapAddress();
//        mapAddress.setDetails(geocode.getText("formatted_address"));
//        mapAddress.setLongitude(geocode.getText("location").split(",")[0]);
//        mapAddress.setLatitude(geocode.getText("location").split(",")[1]);
//        geocode.getText("province");
//        mapAddress.setAdministrativeAreaCode("location_" + geocode.getText("location"));
//        mapAddress.setAdministrativeArea(geocode.getText("country") + geocode.getText("province") + geocode.getText("city") + geocode.getText("district"));
//        return mapAddress;
//    }

    public String getDistance(String origin, String destination, Integer nosteps) throws Exception {
        StringBuilder result = new StringBuilder();
        String reqUrl = String.format("https://restapi.amap.com/v3/direction/driving?key=%s&origin=%s&destination=%s&nosteps=%s", amapKey, origin, destination, nosteps);
        log.info("reqUrl.{}", reqUrl);
        URL url = new URL(reqUrl);
        URLConnection conn = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        in.close();
        log.info("result.{}", result);
        MapModel<String, Object> map = JsonObject.toMap(result.toString());
        if (!"1".equals(map.getText("status"))) {
            throw new BusinessException("计算距离失败");
        }
        MapModel<String, Object> route = JsonObject.toMap(map.get("route"));
        List<String> paths = JsonObject.toList(route.get("paths"));
        if (paths == null || paths.size() == 0) {
            throw new BusinessException("计算距离失败");
        }
        return JsonObject.toMap(paths.get(0)).getText("distance");
    }
}